<!-- 商品列表 -->
<template>
    <div class="common-layout">
        <el-backtop :bottom="50" target=".main" ref="backTop" :visibility-height="10"></el-backtop>
        <el-container>
            <el-header>
                <el-space>
                    <el-input class="fix_input" v-model.trim="seacherData.title" type="text" autocomplete="off"
                        placeholder="请输入商品名称" clearable @clear="init()" />
                    <el-input class="fix_input" v-model.trim="seacherData.barcode" type="text" autocomplete="off"
                        placeholder="请输入商品条形码" clearable @clear="init()" />
                    <el-select class="frame" placeholder="请选择商品状态" v-model="seacherData.status">
                        <el-option v-for="item in groupStatus" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-cascader placeholder="请选择商品类目" :options="options" clearable :props="prop"
                        v-model="seacherData.categoryId" />
                    <el-button :icon="Search" type="primary" @click="search()">查找</el-button>
                    <el-button :icon="Plus" type="primary" @click="addRole();">添加</el-button>
                </el-space>
            </el-header>
            <el-main>
                <div class="el-scrollbar__wrap metaBox">
                    <el-backtop :bottom="100" ref="backTop" :visibility-height="5" target=".metaBox .el-scrollbar__wrap" />
                    <!-- 表格组件 -->
                    <el-table :data="tableData" border style="width: 100%;height: 100%;" class="scrollbar-demo-item"
                        v-loading="listLoading" element-londing-text="正在加载中...">
                        <el-table-column type="selection" />
                        <el-table-column type="expand" label="sku信息" style="width:100%">
                            <template #default="scope">
                                <el-descriptions :column="1" border>
                                    <el-descriptions-item label="类目ID" align="left" width="110px">
                                        <span>{{ scope.row.categoryId }}</span>
                                    </el-descriptions-item>
                                    <el-descriptions-item label="sku信息" align="center">
                                        <el-table :data="scope.row.skuList" :header-cell-style="{ 'text-align': 'center' }"
                                            id="table" :cell-style="{ 'text-align': 'center' }">
                                            <el-table-column label="商品条码" prop="barCode" />
                                            <el-table-column label="商品规格" prop="title" />
                                            <el-table-column label="商品库存" prop="stock" />
                                            <el-table-column label="原价" prop="originalPrice" />
                                            <el-table-column label="现价" prop="price" />
                                        </el-table>
                                    </el-descriptions-item>
                                </el-descriptions>
                            </template>
                        </el-table-column>

                        <el-table-column prop="id" label="商品ID" align="center" />
                        <el-table-column prop="title" label="商品名称" align="center" width="200" />
                        <el-table-column prop="img" label="图片" align="center" width="100">
                            <template #default="scope">
                                <el-popover trigger="hover" placement="right" v-if="scope.row.img">
                                    <template #reference>
                                        <el-image :src="scope.row.img" style="width:35px;height:50px;" />
                                    </template>
                                    <template #default>
                                        <el-image :src="scope.row.img" style="width:148px;height:180px;" />
                                    </template>
                                </el-popover>
                                <el-tag type="info" v-else>类型无需图片</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="spuId" label="商品信息介绍" align="center" width="120">
                            <template #default="scope">
                                <el-button type="primary" @click="handleSee(scope.row)">查看</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column prop="categoryId" label="类目ID" align="center" />
                        <el-table-column prop="freightTemplateId" label="邮费模板ID" align="center" width="100"/>
                        <el-table-column prop="sales" label="销量" align="center" width="100" />
                        <el-table-column prop="unit" label="单位" align="center" width="100" />
                        <el-table-column label="是否在售" prop="status" width="100">
                            <template #default="scope">
                                <el-tag :type="scope.row.status == 1 ? 'success' : 'warning'">{{ scope.row.status == 1 ?
                                    "在售" : '下架' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column prop="description" label="描述" align="center" width="100" />
                        <el-table-column label="操作" align="center" width="180">
                            <template #default="scope">
                                <el-button type='primary' @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button @click="handleShelf(scope.$index, scope.row)"
                                    :type="scope.row.status == 1 ? 'warning' : 'primary'">
                                    {{ scope.row.status == 1 ? '下架' : '上架' }}</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 查看框 -->
                    <el-dialog title="商品详情" v-model="see" width="75%" @close="see == false?detail = '':''">
                        <div v-html="detail" style="text-align: center; overflow: hidden;"></div>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="see = false">取消</el-button>
                        </div>
                    </el-dialog>
                </div>
            </el-main>
            <el-footer>
                <Paging v-bind="pagination" @page-change="pageChange" />
            </el-footer>
        </el-container>
    </div>
</template>
  
<script lang="ts" setup>
import { Search, Plus } from '@element-plus/icons-vue'

import { post } from '@/utils/http';
import { nextTick, onMounted, reactive, ref } from 'vue';
import Paging from '@/components/paging/Paging.vue'
import { ClassPagination, classproduct } from '#/index';
import { ElMessage, ElMessageBox, ElNotification } from "element-plus"
import router from '@/router';
// 数据初始化
onMounted(() => {
    init()
})
const see = ref(false)                    //查看框
const detail = ref('')                             //查看框数据
const backTop = ref()                                   //回到顶部
const pagination = reactive(new ClassPagination())      //分页
let listLoading = ref(false)            //加载效果
const options: Array<any> = reactive([])       //类目树结构
const tableData: classproduct[] = reactive([])    //表格数据

/**
* 搜索所需的数据
*/
let seacherData = reactive({
    barcode: "",      //商品列表的ID
    title: '',        //商品列表的名称
    status: '',       //商品列表的状态
    categoryId: ''     //商品列表类目
})

//搜索商品
const groupStatus = [
    { value: 1, name: '在售' },
    { value: 0, name: '下架' }
]

/**
 * 类目树配置选项
 */
const prop = {
    emitPath: false,
    children: "childrenList",
    value: "id",
    label: "title"
}
getCategory()
/**
 * 请求类目数据
 */
function getCategory() {
    post({
        _gp: "admin.category",
        _mt: "categoryTree"
    }).then(res => {
        let { errmsg, errno, data } = res
        if (200 == errno) {
            options.length = 0
            options.push(...data)
        } else {
            ElMessage.error(errmsg)
        }

    })
}

/**
 * 获取初始化数据，用于渲染页面
 */
function init() {
    listLoading.value = true
    // 请求管理员列表需要传递的参数
    let productListData = reactive({
        _gp: "admin.product",
        _mt: "list",
        title: seacherData.title,              //搜索标题
        status: seacherData.status,             //商品状态
        categoryId: seacherData.categoryId,         //搜索类目
        barcode: seacherData.barcode,            //商品条形码
        page: pagination.page,//当前页码
        limit: pagination.limit//每页页码长度
    })
    // 请求管理员列表接口拿到管理员列表信息
    post(productListData).then(res => {
        console.log("====管理员数据======");
        console.log(res);
        let { data: { total, items }, errno, errmsg } = res
        if (200 === errno) {
            pagination.total = total
            console.log(items);
            tableData.length = 0;

            tableData.push(...items)
            listLoading.value = false
            nextTick(() => {
                backTop.value.$el.click?.()
            })
        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => {
        console.log(err);

    })
}

// 搜索操作
function search() {
    init()
}

//子传父的自定义事件
function pageChange(e: TypePage) {
    pagination.page = e.page
    pagination.limit = e.limit
    init()
}

/**
 * 查看信息
 */
function handleSee(row: classproduct) {
    
    post({
        _gp: 'admin.product',
        _mt: 'detail',
        spuId: row.id
    }).then(res => {
        if (200 == res.errno) {
            detail.value = res.data.detail
            if (detail.value) {
                see.value = true
            }
        } else {
            ElMessage.error(res.errmsg)
        }
    })
}

getGoodsData()

/**
 * 请求商品数据
 */
function getGoodsData() {
    post({
        _gp: "admin.category",
        _mt: "categoryTree"
    }).then(res => {
        console.log(res.data)
        let { errmsg, errno } = res
        if (200 == errno) {
            options.length = 0
            options.push(...res.data)

        } else {
            ElMessage.error(errmsg)
        }

    })
}

/**
 * 点击添加
 */
function addRole() {
    router.push({ name: 'productCreate' })
}
/**
 * 点击编辑
 */
function handleEdit(index: number, row: classproduct) {
    router.push({
        name: 'productEdit',
        params: {
            id: row.id
        }
    })
}


/**
 * 上架或者下架
 * @param index 当前下标
 * @param row 当前下标的数据
 */
const handleShelf = (index: number, row: classproduct) => {

    let data = {
        _gp: 'admin.product',
        _mt: 'freezeOrActivation',
        spuId: row.id,
        status: row.status == 1 ? 0 : 1
    }
    let cz = ref("")
    if (row.status == 1) {
        cz.value = "冻结"
    } else {
        cz.value = "激活"
    }
    ElMessageBox.confirm('此操作将' + cz.value + row.title + ' , 是否继续？')
        .then(() => {
            post(data).then(res => {
                console.log(res);

                let { errno, errmsg } = res
                if (200 === errno) {
                    ElNotification.success(row.status == 0 ? '上架成功' : '下架成功')
                    init()
                } else {
                    ElMessage.error(errmsg)
                }
            }).catch(err => {
                ElMessage.error(err)
            })
        })
        .catch(() => {
            ElMessage.error("取消操作！")
        })

}

</script>
  

<style scoped lang="less">
.metaBox {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60vh;
    text-align: center;
}

.fix_input {
    width: 200px;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.box-card {
    width: 100%;
}
</style>